package com.itita.ww2.model.user;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itita.ww2.enums.ChannelEnum;
import com.itita.ww2.game.alliance.AllianceManager;
import com.itita.ww2.game.user.UserArmyManager;
import com.itita.ww2.game.user.UserBattleManager;
import com.itita.ww2.game.user.UserBuildingManager;
import com.itita.ww2.game.user.UserDevTimeManager;
import com.itita.ww2.game.user.UserInfo;
import com.itita.ww2.game.user.UserInventoryManager;
import com.itita.ww2.game.user.UserMissionManager;
import com.itita.ww2.game.user.UserResource;
import com.itita.ww2.game.user.UserRewardDispatch;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.game.user.UserWorldMapManager;
import com.itita.ww2.game.user.insideevent.UserInsideEventManager;
import com.itita.ww2.game.user.payment.UserPayManager;
import com.itita.ww2.model.LoginInfo;
import com.itita.ww2.model.area.AreaDefault;
import com.itita.ww2.model.area.BaseArea;
import com.itita.ww2.utils.TimeUtil;
import com.smartfoxserver.v2.SmartFoxServer;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;

/**
 * 用户配置(在线用户)
 * @author NorthLan
 *
 */
public class UserProfile {
	private static final Logger logger = LoggerFactory.getLogger(UserProfile.class);
	/*
	 *  profile
	 */
	private int uid; // db_uid
	private String username; // 用户名
	private String nickname; // 昵称
	private String country; // 国家代码
	private int channel; // 渠道号
	private String channelId; // 渠道id
	/*
	 *  time
	 */
	// private long lastChatTime; // 最近聊天时间
	private long lastLoginTime; // 最近登录时间

	private String aid; // 联盟id
	// sfs
	private volatile transient User sfsUser;

	/*
	 *  in-game
	 */
	private transient BaseArea curArea; // 当前用户所在区域
	//
	private transient UserResource userResource; // 资源管理器
	private transient UserInventoryManager userInventory; // 玩家背包
	private transient UserInfo userInfo; // 玩家信息
	private transient UserBuildingManager bdManager; // 建筑管理器
	private transient UserArmyManager armyManager; // 兵管理器
	// private transient UserScienceManager scienceManager; // 科技管理器
	private transient UserDevTimeManager timeManager; // 时间管理器
	private transient UserBattleManager battleMgr; // 战斗管理器
	private transient UserWorldMapManager wmManager; // 玩家世界地图数据管理器
	private transient UserMissionManager missionMgr; // 任务(关卡)管理器
	private transient UserPayManager payMgr; // 支付管理
	// 
	private transient UserRewardDispatch rewardMgr; // (资源/道具)奖励管理器
	private transient UserInsideEventManager insideEventMgr; // 内部事件监听器

	public UserProfile(int uid) {
		this.uid = uid;
		this.curArea = new AreaDefault(); // 处于默认区域
		this.aid = "";

	}

	private void initialize() {
		this.userResource = new UserResource(this);
		this.userInventory = new UserInventoryManager(this);
		this.userInfo = new UserInfo(this);
		this.bdManager = new UserBuildingManager(this);
		this.armyManager = new UserArmyManager(this);
		// this.scienceManager = new UserScienceManager(this);
		this.timeManager = new UserDevTimeManager(this);
		this.wmManager = new UserWorldMapManager(this);
		this.missionMgr = new UserMissionManager(this);
		this.payMgr = new UserPayManager(this);
		// 
		this.battleMgr = new UserBattleManager(this);
		this.rewardMgr = new UserRewardDispatch();
		this.insideEventMgr = new UserInsideEventManager();

		// this.scienceManager.initialize();
		// this.scienceManager.load();
		
		this.userInfo.initialize();
		this.userResource.initialize();
		this.userInventory.initialize(); // 
		this.bdManager.initialize(); // 
		this.armyManager.initialize(); // 
		this.timeManager.initialize();
		this.wmManager.initialize();
		this.payMgr.initialize();
	}

	/**
	 * 用户登录,生成Profile,缓存至内存
	 */
	public static UserProfile handleLogin(User user) {
		LoginInfo loginInfo = (LoginInfo) user.getSession().getProperty("loginInfo");
		user.getSession().removeProperty("logininfo"); // 移除登录信息
		// 设置数据
		UserProfile profile = new UserProfile(loginInfo.uid);
		profile.username = loginInfo.username;
		profile.nickname = loginInfo.nickname;
		profile.country = loginInfo.country;
		profile.channel = loginInfo.channel;
		profile.channelId = loginInfo.channelId;
		// 
		profile.sfsUser = user;
		// time
		profile.lastLoginTime = TimeUtil.getUtcNow().getMillis();
		// alliance
		profile.aid = AllianceManager.getInstance().getAidByUid(profile.getUid());

		profile.initialize();

		// set user property
		user.setProperty("uid", profile.uid);
		user.setProperty("country", profile.country);

		logger.debug("[Name:{} uid:{}] handleLogin.", profile.nickname, profile.uid);
		return profile;
	}

	/**
	 * 延迟加载(是否登录需要经过验证)
	 */
	public static UserProfile handleLazy(int uid) {
		// 查询用户信息
		ISFSObject uData = UserService.getInstance().getUserData(uid);
		if (uData == null) {
			logger.error("{} Get user data failure... uid: {}", "UserProfile", uid);
			return null;
		}
		UserProfile profile = new UserProfile(uid);

		profile.username = uData.getUtfString("username");
		profile.nickname = uData.getUtfString("nickname");
		profile.country = uData.getUtfString("country");
		profile.channel = uData.getInt("channel");
		profile.channelId = uData.getUtfString("channelId");
		profile.sfsUser = SmartFoxServer.getInstance().getUserManager().getUserByName(profile.nickname);
		// time
		profile.lastLoginTime = uData.getLong("lastTime");
		// alliance
		profile.aid = AllianceManager.getInstance().getAidByUid(profile.getUid());

		// set user property
		if (profile.isLogin()) {
			profile.sfsUser.setProperty("uid", profile.uid);
			profile.sfsUser.setProperty("country", profile.country);
		}
		profile.initialize();

		logger.debug("[Name:{} uid:{}] handleLazy.", profile.nickname, profile.uid);
		return profile;
	}

	/**
	 * 绑定帐号到渠道
	 */
	public boolean bind(int channel, String channelId) {
		this.channel = channel;
		this.channelId = channelId;
		// sql
		return UserService.getInstance().bind(this.uid, this.channel, this.channelId);
	}

	/**
	 * 用户离线
	 */
	public void onDisconnectEvent() {
		// 战斗
		this.battleMgr.onDisconnectEvent();
	}

	/////////////////////////////////////
	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj instanceof UserProfile) {
			return this.uid == ((UserProfile) obj).getUid();
		}
		return false;
	}

	public int getUid() {
		return this.uid;
	}

	public String getNickname() {
		return this.nickname;
	}

	public String getUsername() {
		return this.username;
	}

	public String getCountry() {
		return this.country;
	}

	public boolean isLogin() {
		return this.sfsUser != null;
	}

	public boolean isBindAccount() {
		return channel != ChannelEnum.OFFICIAL.getValue() && channel != ChannelEnum.DEFAULT.getValue();
	}

	public boolean isSetNickname() {
		return !username.equals(nickname);
	}

	public User getSFSUser() {
		return this.sfsUser;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
		if (this.sfsUser != null) {
			this.sfsUser.setName(nickname);
		}
	}

	public String getChannelId() {
		return channelId;
	}

	public DateTime getLastLoginTime() {
		return new DateTime(this.lastLoginTime);
	}

	public boolean isJoinAlliance() {
		return StringUtils.isNotBlank(this.aid);
	}

	public String getAid() {
		return this.aid;
	}

	public int getChannel() {
		return channel;
	}

	public void setAid(String aid) {
		this.aid = aid;
	}

	public void setCurArea(BaseArea area) {
		this.curArea = area;
	}

	public BaseArea getCurArea() {
		return this.curArea;
	}

	public UserBattleManager getBattleManager() {
		return this.battleMgr;
	}

	public UserResource getResManager() {
		return this.userResource;
	}

	public UserInventoryManager getInventory() {
		return this.userInventory;
	}

	public UserBuildingManager getBDManager() {
		return this.bdManager;
	}

	public UserArmyManager getArmyManager() {
		return this.armyManager;
	}

	//	public UserScienceManager getScManager() {
	//		return this.scienceManager;
	//	}

	public UserDevTimeManager getTimeManager() {
		return this.timeManager;
	}

	public UserInfo getUserInfo() {
		return this.userInfo;
	}

	public UserWorldMapManager getWMManager() {
		return this.wmManager;
	}

	public UserMissionManager getMissionManager() {
		return this.missionMgr;
	}

	public final UserRewardDispatch getRewardManager() {
		return rewardMgr;
	}

	public UserInsideEventManager getInsideEventMgr() {
		return insideEventMgr;
	}

	public UserPayManager getPaymentMgr() {
		return payMgr;
	}
}
